/*
 *    Copyright (c) 2018-2025, envpro All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: envpro
 */

package com.iwomy.envpro.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iwomy.envpro.admin.api.dto.SysTenantDTO;
import com.iwomy.envpro.admin.api.entity.SysTenant;
import com.iwomy.envpro.admin.api.entity.SysUser;
import com.iwomy.envpro.admin.api.vo.SysTenantVo;
import com.iwomy.envpro.admin.service.SysTenantService;
import com.iwomy.envpro.admin.service.SysUserService;
import com.iwomy.envpro.common.core.constant.CacheConstants;
import com.iwomy.envpro.common.core.constant.CommonConstants;
import com.iwomy.envpro.common.core.constant.SecurityConstants;
import com.iwomy.envpro.common.core.util.R;
import com.iwomy.envpro.common.data.tenant.TenantContextHolder;
import com.iwomy.envpro.common.excel.annotation.ResponseExcel;
import com.iwomy.envpro.common.log.annotation.SysLog;
import com.iwomy.envpro.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 租户管理
 *
 * @author envpro
 * @date 2019-05-15 15:55:41
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tenant")
@Tag(description = "tenant", name = "租户管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysTenantController {

	private final SysTenantService sysTenantService;

	private final SysUserService sysUserService;

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param sysTenant 租户
	 * @return
	 */
	@GetMapping("/page")
	public R getSysTenantPage(@ParameterObject Page page, @ParameterObject SysTenant sysTenant) {


		return R.ok(sysTenantService.getSysTenantPage(page, sysTenant));
	}

	/**
	 * 通过ID 查询租户信息
	 *
	 * @param id ID
	 * @return R
	 */
	@GetMapping("/details/{id}")
	public R getById(@PathVariable Long id) {


		SysTenant one = sysTenantService.getById(id);
		TenantContextHolder.setTenantSkip();
		LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(SysUser::getTenantId, one.getId());
		wrapper.eq(SysUser::getDefaultAccount, 20);
		SysUser sysUser = sysUserService.getOne(wrapper);
		SysTenantVo sysTenantVo = BeanUtil.copyProperties(one, SysTenantVo.class);
		sysTenantVo.setPhone(ObjectUtil.isNull(sysUser) ? null : sysUser.getPhone());
		return R.ok(sysTenantVo);
	}

	/**
	 * 查询租户信息
	 *
	 * @param query 查询条件
	 * @return 租户信息
	 */
	@GetMapping("/details")
	public R getDetails(@ParameterObject SysTenant query) {
		SysTenant one = sysTenantService.getOne(Wrappers.query(query), false);
		if (ObjectUtil.isNull(one)) return R.ok(one);
		LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ObjectUtil.isNotNull(one.getId()), SysUser::getTenantId, one.getId());
		wrapper.eq(SysUser::getDefaultAccount, 20);
		SysUser sysUser = sysUserService.getOne(wrapper);
		SysTenantVo sysTenantVo = BeanUtil.copyProperties(one, SysTenantVo.class);
		sysTenantVo.setPhone(ObjectUtil.isNull(sysUser) ? null : sysUser.getPhone());
		return R.ok(sysTenantVo);
	}

	/**
	 * 新增租户
	 *
	 * @param sysTenant 租户
	 * @return R
	 */
	@SysLog("新增租户")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_systenant_add')")
	@CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
	public R save(@RequestBody SysTenantDTO sysTenant) throws Exception {
		return R.ok(sysTenantService.saveTenant(sysTenant));
	}

	/**
	 * 修改租户
	 *
	 * @param sysTenant 租户
	 * @return R
	 */
	@SysLog("修改租户")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_systenant_edit')")
	@CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
	public R update(@RequestBody SysTenant sysTenant) {
		//使用量不允许修改
		sysTenant.setUsedDevice(null);
		sysTenant.setUsedUsers(null);
		sysTenant.setUsedSms(null);
		sysTenant.setUsedVoice(null);
		return R.ok(sysTenantService.updateTenant(sysTenant));
	}

	/**
	 * 通过id删除租户
	 * <p>
	 * 为了保证安全,这里只删除租户表的数据，不删除基础表中的租户初始化数据。
	 *
	 * @param ids id 列表
	 * @return R
	 */
	@SysLog("删除租户")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('sys_systenant_del')")
	@CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
	public R removeById(@RequestBody Long[] ids) {

		LambdaUpdateWrapper<SysTenant> update = Wrappers.lambdaUpdate();
		update.set(SysTenant::getStatus, CommonConstants.STATUS_DEL);
		update.in(SysTenant::getId, CollUtil.toList(ids));
		sysTenantService.update(update);
		return R.ok(sysTenantService.removeBatchByIds(CollUtil.toList(ids)));
	}

	/**
	 * 查询全部有效的租户
	 *
	 * @return
	 */
	@Inner(value = false)
	@GetMapping("/list")
	public R list() {
		List<SysTenant> tenants = sysTenantService.getNormalTenant().stream()
				.filter(tenant -> tenant.getStartTime().isBefore(LocalDateTime.now()))
				.filter(tenant -> tenant.getEndTime().isAfter(LocalDateTime.now())).collect(Collectors.toList());
		return R.ok(tenants);
	}

	/**
	 * 导出excel 表格
	 *
	 * @return
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('sys_systenant_export')")
	public List<SysTenant> export(SysTenant sysTenant) {
		return sysTenantService.list(Wrappers.query(sysTenant));
	}


	/**
	 * 通过ID 查询租户信息
	 *
	 * @param username username
	 * @return R
	 */
	@GetMapping("/getListByUsername")
	@Inner(value = false)
	public R getListByUsername(@RequestParam String username, @RequestHeader(SecurityConstants.TYPE) Integer type) {
		return R.ok(sysTenantService.getTenants(username, type));
	}


	/**
	 * 修改租户
	 *
	 * @param sysTenant 租户
	 * @return R
	 */
	@PutMapping("updateTenant")
	@Inner
	@CacheEvict(value = CacheConstants.TENANT_DETAILS, allEntries = true)
	public R updateTenant(@RequestBody SysTenant sysTenant) {
		return R.ok(sysTenantService.updateTenant(sysTenant));
	}


	/**
	 * 通过ID 查询租户信息
	 *
	 * @param id ID
	 * @return R
	 */
	@Inner
	@GetMapping("/innerDetails/{id}")
	public R innerDetails(@PathVariable Long id) {
		return R.ok(sysTenantService.getById(id));
	}

}
